package com.telsoft.hms.lib.data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;

public class ConnectionFactory {
	private static DBPool dbPool;
	private static Connection connection;

	public static Connection getConnection(String key) throws Exception {
		// String strNameDBPool = com.telsoft.hms.util.StringUtil
		// .getPropValues("dbpool.properties");
		String strNameDBPool;
		ResourceBundle rsNameDBPool = ResourceBundle.getBundle("dbpool");
		strNameDBPool = rsNameDBPool.getString("name");
		// return bundle.getString(keyword);
		if (dbPool == null) {
			dbPool = new DBPool(strNameDBPool);

			// dbPool = DBPool.getInstance(strNameDBPool);
		}
		connection = dbPool.getConnectionFromPoolManager(key);
		return connection;
	}

	public static int getSessionLogin(String strCode) throws Exception {
		// String strNameDBPool = com.telsoft.hms.util.StringUtil
		// .getPropValues("dbpool.properties");
		String strNameDBPool;
		ResourceBundle rsNameDBPool = ResourceBundle.getBundle("dbpool");
		strNameDBPool = rsNameDBPool.getString("name");
		if (dbPool == null) {
			dbPool = new DBPool(strNameDBPool);

			// dbPool = DBPool.getInstance(strNameDBPool);
		}
		// if (dbPool == null) {
		// dbPool = DBPool.getInstance(strNameDBPool);
		// }
		Connection con = dbPool.getConn(strNameDBPool);
		String strSQL = "SELECT a.value FROM hms_restriction a, remap_db_info b, remap_schema c"
				+ " WHERE c.remap_schema_id = b.remap_schema_id AND b.remap_schema_id = a.remap_schema_id"
				+ " AND a.TYPE = 'SESSION' AND c.code = ?";
		PreparedStatement stm = null;
		ResultSet rs = null;
		int iMaxSessionLogin = 0;
		try {
			stm = con.prepareStatement(strSQL);
			stm.setString(1, strCode);
			rs = stm.executeQuery();
			if (rs.next()) {
				iMaxSessionLogin = rs.getInt("value");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw e;
		} finally {
			rs.close();
			stm.close();
			con.close();
		}
		return iMaxSessionLogin;
	}
}
